<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

use App\Http\Models\CacheModel;
use Illuminate\Support\Facades\Redis;

class ProjectModel extends Model
{
    const STATUS_DELETE  = 0;
    const STATUS_PUBLISH = 2;
    const STATUS_ACTIVE  = 1;

    const CACHE_KEY = 'project:';

	protected $connection = 'db_main';

	protected $table = 'wp_gcreator_project';

    protected static $_projectConfingKey = 'appid:config:raffle:';

	public $timestamps = false;

    protected $fillable = ['name', 'title', 'uid', 'desc', 'username', 'token', 'template_id', 'iscollect', 'setrankbtn', 'create_time', 'modify_time', 'status', 'icon_url', 'category', 'raffletype', 'endtime'];

    // 获取用户创建项目个数
    public static function count($uid)
    {
        return self::where(["uid" => $uid]) ->having('status', '>', self::STATUS_DELETE) ->get() -> count();
    }

    // 删除项目
    public static function remove($uid, $token)
    {
        CacheModel::del(self::CACHE_KEY . $token);
        return self::where(["uid" => $uid, "token" => $token])->update(["status" => self::STATUS_DELETE]);
    }

    // INFO
    public static function info($token)
    {
        if ($info = CacheModel::get(self::CACHE_KEY . $token))
        {
            return json_decode($info);
        } else {
            $info = self::where(["token" => $token])->first();
            if($info){
                CacheModel::set(self::CACHE_KEY . $token, json_encode($info));
            }
            return $info;
        }
    }


    /**
     * 编辑页面获取所有项目设置信息
     * @return array(
     *      'marketinginfo'=>array(...),
     *      'shareinfo'=>array(...),
     *      'offlineinfo'=>array(...)
     *  );
     */
    public static function getAllProjectSettingInfo ( $appid, $token , $caseTempName = '', $template_id = 0 ) {
        $marketingInfo = array(
            'isset'         => 1,
            'type'          => 4,
            'linkname'      => '我也要用赢销+免费制作',
            'linkpath'      => 'http://www.beetobees.com/m/index.html?acode='.$token,
            'imageurl'      => 'adImg.png',
            'imagepath'     => 'http://www.beetobees.com/m/index.html?acode='.$token,
            'qrcodeurl'     => 'adImg.png',
            'qrcodepath'    => 'qrcode.png',
            'unionname'     => '游戏化营销专家',
            'unionpath'     => 'http://www.beetobees.com/m/index.html?acode='.$token,
            'basename'      => '赢销+技术支持',
            'basepath'      => 'http://www.beetobees.com/m/index.html?acode='.$token,
            'rule_show'     => 'true',
            'redicturl'     => 'resource/assets/about.png',
            'redictpath'    => 'http://www.beetobees.com/m/index.html?acode='.$token,
            'promotion_isset'   => 1,
            'promotion_type'    => 1
        );

        $shareInfo = array(
            'title'=>'',
            'desc'=>'',
            'link'=>'icon.png',
            'finishdesc'=>''
        );

        $offlineInfo = array(
            'time' => 0,
            'desc' => '活动已结束，敬请关注更多精彩！'
        );

        $redis = Redis::connection('db_main');
        $marketinginfo  = $redis->hgetall(self::$_projectConfingKey.$appid.':marketinginfo');
        $shareinfo      = $redis->hgetall(self::$_projectConfingKey.$appid.':shareinfo');
        $offlineinfo    = $redis->hgetall(self::$_projectConfingKey.$appid.':offlineinfo');

        if(!$marketinginfo || !$shareinfo || !$offlineinfo) {
            $baseinfo = $baseinfo ? $baseinfo : SettingsModel::getItemValue($appid, 'baseinfo', '');
            if($baseinfo) {
                $baseInfos = json_decode($baseinfo, true);
                if(is_array($baseInfos)) {
                    if(!$marketinginfo || !$marketinginfo['isset']) {
                        $marketinginfo  = isset($baseInfos['marketinginfo']) ? $baseInfos['marketinginfo'] : array();
                        self::saveMarketingInfoToRedis( $appid, $marketinginfo);
                    }
                    if(!$shareinfo || (!$shareinfo['title'] && !$shareinfo['desc'])) {
                        $shareinfo      = isset($baseInfos['shareinfo']) ? $baseInfos['shareinfo'] : array();
                        self::saveShareInfoToRedis( $appid, $shareinfo);
                    }

                    if(!$offlineinfo || (!$offlineinfo['time'] && !$offlineinfo['desc'])) {
                        $offlineinfo    = isset($baseInfos['offlineinfo']) ? $baseInfos['offlineinfo'] : array();
                        self::saveOfflineInfoToRedis( $appid, $offlineinfo);
                    }
                }

            } else {
                if(!$shareinfo || (!$shareinfo['title'] && !$shareinfo['desc'])) {
                    if($template_id){
                        //获取模板分享设置信息
                        $model_arr = TemplateModel::select(array("share_title","share_nofinish_desc","share_finish_desc"))->where( ["id"=>$template_id])->first();
                    }
                    if($model_arr['share_title']!==''){
                        $shareinfo = array(
                            'title' => $model_arr['share_title'],
                            'desc'  => $model_arr['share_nofinish_desc'],
                            'link'  =>'icon.png',
                            'finishdesc' => $model_arr['share_finish_desc']
                        );
                    }else{
                        $templateJson = TemplateJsonModel::readTemplateJson($token, $caseTempName);
                        $shareinfo = array(
                            'title' => $templateJson['share']['wechat']['title'],
                            'desc'  => $templateJson['share']['wechat']['desc'],
                            'link'  =>'icon.png',
                            'finishdesc' => $templateJson['share']['shareAfter']['desc']
                        );
                    }
                }
            }
        }

        preg_match_all('/{[\x80-\xff|\w]+}/', $shareinfo['finishdesc'], $matches);
        $replacearr = array();
        if($matches[0]){
            $replacearr = array_unique($matches[0]);
            foreach ($replacearr as $key => $item) {
                if(!in_array($item, array('{积分}','{称号}'))){
                    unset($replacearr[$key]);
                }else{
                    $replacearr[$key] = str_replace(array('{','}'), '', $item);
                }
            }
        }

        $marketinginfo  = array_merge($marketingInfo, $marketinginfo);

        //处理URL链接中的特殊字符
        $marketinginfo['redictpath']= str_replace("&amp;", "&", trim($marketinginfo['redictpath']));
        $marketinginfo['linkpath']= str_replace("&amp;", "&", trim($marketinginfo['linkpath']));
        $marketinginfo['unionpath']= str_replace("&amp;", "&", trim($marketinginfo['unionpath']));

        $shareinfo      = array_merge($shareInfo, $shareinfo);
        $offlineinfo    = array_merge($offlineInfo, $offlineinfo);

        return array('code'=>0, 'msg'=>'', 'data'=>array(
            'marketinginfo' => $marketinginfo,
            'shareinfo' => $shareinfo,
            'offlineinfo' => $offlineinfo,
            'replacearr' => $replacearr
        ));
    }

    // 保存营销信息到redis
    public static function saveMarketingInfoToRedis ( $appid, $info ) {
        $marketingInfo      = array();
        $redisKey           = self::$_projectConfingKey . $appid . ':marketinginfo';

        $marketingInfo['isset']         = isset($info['isset'])         ? $info['isset']        : 1;
        $marketingInfo['type']          = isset($info['type'])          ? $info['type']         : 1;
        $marketingInfo['linkname']      = isset($info['linkname'])      ? $info['linkname']     : '';
        $marketingInfo['linkpath']      = isset($info['linkpath'])      ? $info['linkpath']     : '';
        $marketingInfo['imageurl']      = isset($info['imageurl'])      ? $info['imageurl']     : '';
        $marketingInfo['imagepath']     = isset($info['imagepath'])     ? $info['imagepath']    : '';

        $marketingInfo['unionname']     = isset($info['unionname'])     ? $info['unionname']    : '';
        $marketingInfo['unionpath']     = isset($info['unionpath'])     ? $info['unionpath']    : '';
        $marketingInfo['rule_show']     = isset($info['rule_show'])     ? $info['rule_show']    : 'true';

        //关注我们功能设置
        $marketingInfo['qrcodeurl']     = isset($info['qrcodeurl'])     ? $info['qrcodeurl']    : '';
        $marketingInfo['redicturl']     = isset($info['redicturl'])     ? $info['redicturl']    : '';
        $marketingInfo['qrcodepath']    = isset($info['qrcodepath'])    ? $info['qrcodepath']   : '';
        $marketingInfo['redictpath']    = isset($info['redictpath'])    ? $info['redictpath']   : '';
        $marketingInfo['promotion_isset']   = isset($info['promotion_isset']) ? $info['promotion_isset'] : 1;
        $marketingInfo['promotion_type']    = isset($info['promotion_type']) ? $info['promotion_type'] : 1;

        $redis = Redis::connection('db_cache');
        $ret = $redis->hmset($redisKey, $marketingInfo);
        if( $ret ){
            return array('code'=>0, 'msg'=>'', 'data'=>$marketingInfo );
        }else{
            return array('code'=>1, 'msg'=>'保存营销信息失败', 'data'=>array() );
        }
    }

    // 保存分享信息到redis
    public static function saveShareInfoToRedis ( $appid, $info ) {
        $shareInfo  = array();
        $redisKey   = self::$_projectConfingKey . $appid . ':shareinfo';

        $shareInfo['title']         = isset($info['title'])         ? $info['title']        : '';
        $shareInfo['desc']          = isset($info['desc'])          ? $info['desc']         : '';
        $shareInfo['link']          = isset($info['link'])          ? $info['link']         : '';
        $shareInfo['finishdesc']    = isset($info['finishdesc'])    ? $info['finishdesc']   : '';

        $redis = Redis::connection('db_cache');
        $ret = $redis->hmset($redisKey, $shareInfo);
        if( $ret ){
            return array('code'=>1, 'msg'=>'分享信息', 'data'=>array() );
        }else{
            return array('code'=>0, 'msg'=>'', 'data'=>$shareInfo );
        }
    }

    /**
     * 保存离线信息到redis
     * @param $appid
     * @param $info
     * @return array
     */
    public static function saveOfflineInfoToRedis ($appid, $info ) {
        $offlineInfo    = array();
        $redisKey       = self::$_projectConfingKey . $appid . ':offlineinfo';

        $offlineInfo['time']          = isset($info['time'])          ? $info['time']         : '';
        $offlineInfo['desc']          = isset($info['desc'])          ? $info['desc']         : '';

        $redis = Redis::connection('db_cache');
        $ret = $redis->hmset($redisKey, $offlineInfo);
        if( $ret )
            return array('code'=>0, 'msg'=>'', 'data'=>$offlineInfo );

        return array('code'=>1, 'msg'=>'保存离线信息失败', 'data'=>array() );
    }





    // 更新指定key的值，如果存在，则更新，否则插入
    public static function updateItemValue($appid, $fields, $isupdatetime = 1) {
        $map = array();
        $map['id'] = $appid;
        $map['status'] = array('neq', self::STATUS_DELETE);

        if($appid && is_array($fields)) {
            if($isupdatetime) $fields = array_merge($fields, array('modify_time'=>time()));
            return self::where($map)->update($fields);
        } else{
            return false;
        }
    }

    /**
     * 将分享信息存入template.json和项目表中
     */
    public static function syncShareInfo($appid, $templateName='', $token, $shareInfo){
        $templateJson = TemplateJsonModel::read($token, $templateName);

        $templateJson['share']['wechat']['title']       = $shareInfo['title'];
        $templateJson['share']['wechat']['desc']        = $shareInfo['desc'];
        $templateJson['share']['shareAfter']['title']   = $shareInfo['title'];
        $templateJson['share']['shareAfter']['desc']    = $shareInfo['finishdesc'];
        $templateJson['share']['shareAfter']['imgUrl']  = 'icon.png';
        $templateJson['share']['setting']['title']      = $shareInfo['title'];
        TemplateJsonModel::write($token, $templateJson);

        self::updateItemValue($appid, ['title'=> $shareInfo['title'], 'desc'=> $shareInfo['desc']] );
    }

    // 通过appid获取项目信息（项目id）
    public static function getInfoByAppid($id, $field = '*') {
        $cache = new CacheModel();
        $data = $cache->getProject($id);
        if(!$data || $data == 'null') {
            $map = array();
            $map['id'] = $id;
            $map['status'] = array('neq', self::STATUS_DELETE);
            $info = self::where($map)->select($field)->first();
            if($info) $cache->setProject($id, json_encode($info));
        } else {
            $info = json_decode($data, true);
        }
        return $info;
    }
}

